package com.mmall.seckill.common.Interceptor;

import com.mmall.seckill.annotation.AccessLimit;
import com.mmall.seckill.common.CodeMsg;
import com.mmall.seckill.common.Result;
import com.mmall.seckill.common.redis.RedisService;
import com.mmall.seckill.common.redis.keyCode.AccessKey;
import com.mmall.seckill.common.redis.keyCode.SeckillUserKey;
import com.mmall.seckill.domain.SeckillUser;
import com.mmall.seckill.util.CookieUtil;
import com.mmall.seckill.util.JsonUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;

/**
 * Created by megan on 2018/8/6.
 * 限流拦截器
 */
@Slf4j
@Service
public class AccessInterceptor extends HandlerInterceptorAdapter {

    @Resource
    private RedisService redisService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if(handler instanceof HandlerMethod){
            SeckillUser user = getUser(request);
            UserContext.setUser(user);
            HandlerMethod hm = (HandlerMethod)handler;
            AccessLimit accessLimit = hm.getMethodAnnotation(AccessLimit.class);
            if(accessLimit == null) {
                return true;
            }
            int seconds = accessLimit.seconds();
            int maxCount = accessLimit.maxCount();
            boolean needLogin = accessLimit.needLogin();
            log.info("正在调用限流拦截器 -> {}, {} 秒内限流 {}次 , 是否需要登录 :{}",request.getRequestURI(),seconds,maxCount,needLogin);
            String key = request.getRequestURI();
            if(needLogin) {
                if(user == null) {
                    render(response, CodeMsg.SESSION_ERROR);
                    return false;
                }
                key += "_" + user.getId();
            }
            AccessKey ak = AccessKey.withExpire(seconds);
            log.info("redisKey -> {}" ,ak+key);
            Integer count = redisService.get(ak, key,Integer.class);
            log.info("{} : 请求次数 -> {} , {} 秒内限流 {}次 ",request.getRequestURI(),count,seconds,maxCount);
            if(count == null) {
                String result = redisService.setEx(ak, key, 1+"");
                log.info("设置值得返回值 -> {}",result);
            }else if(count  < maxCount) {
                redisService.incr(ak, key);
            }else {
                render(response, CodeMsg.ACCESS_LIMIT_REACHED);
                return false;
            }
        }
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        log.info("afterCompletion");
        UserContext.delUser();
    }

    private void render(HttpServletResponse response, CodeMsg cm)throws Exception {
        response.setContentType("application/json;charset=UTF-8");
        OutputStream out = response.getOutputStream();
        String str  = JsonUtil.obj2String(Result.coderMsg(cm));
        out.write(str.getBytes("UTF-8"));
        out.flush();
        out.close();
    }

    private SeckillUser getUser(HttpServletRequest request) {
        String cookieToken = CookieUtil.readLoginToken(request);
        if(StringUtils.isEmpty(cookieToken)){
            return new SeckillUser();
        }
        return JsonUtil.string2Obj(redisService.get(SeckillUserKey.token,cookieToken),SeckillUser.class);
    }


}
